<template id="tinymceee">
    <div style="position: relative;">
        <div style="text-align: right;position: absolute;z-index: 999;right: 0;">
            <el-button size="small" type="primary" @click="openUpload()">上传图片</el-button>
        </div>
        <textarea :id="id_name" style="height:300px" v-model="value"></textarea>
        <el-dialog :visible.sync="centerDialogVisible" width="60%" center>
            <el-tabs v-model="activeName2" type="card">
                <el-tab-pane label="上传图片" name="first">
                    <div
                            style="text-align: center"
                            class="submit_Img"
                            v-loading="imgLoading"
                            element-loading-background="rgba(0, 0, 0, 0)"
                    >
                        <el-upload
                                class="avatar-uploader"
                                action="{!!absolute_admin_url('common.upload.upload',['upload_type'=>'image'])!!}"
                                accept="image/*"
                                :show-file-list="false"
                                :on-success="uploadSuccess"
                                :before-upload="beforeUpload"
                        >
                            <div class="avatar_box" v-if="uploadImgUrl">
                                <img :src="uploadImgUrl" class="avatar" />
                            </div>
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </div>
                </el-tab-pane>
                <el-tab-pane label="浏览图片" name="third">
                    <div>
                        <el-radio-group v-model="radio1" size="medium" @change="chooseYear">
                            <el-radio-button label="">不限</el-radio-button>
                            <el-radio-button label="2020">2020年</el-radio-button>
                            <el-radio-button label="2019">2019年</el-radio-button>
                            <el-radio-button label="2018">2018年</el-radio-button>
                            <el-radio-button label="2017">2017年</el-radio-button>
                            <el-radio-button label="2016">2016年</el-radio-button>
                        </el-radio-group>
                    </div>

                    <div style="margin-top: 10px;">
                        <el-radio-group v-model="radio2" size="small" @change="chooseMonth">
                            <el-radio-button label="">不限</el-radio-button>
                            <el-radio-button label="1">1月</el-radio-button>
                            <el-radio-button label="2">2月</el-radio-button>
                            <el-radio-button label="3">3月</el-radio-button>
                            <el-radio-button label="4">4月</el-radio-button>
                            <el-radio-button label="5">5月</el-radio-button>
                            <el-radio-button label="6">6月</el-radio-button>
                            <el-radio-button label="7">7月</el-radio-button>
                            <el-radio-button label="8">8月</el-radio-button>
                            <el-radio-button label="9">9月</el-radio-button>
                            <el-radio-button label="10">10月</el-radio-button>
                            <el-radio-button label="11">11月</el-radio-button>
                            <el-radio-button label="12">12月</el-radio-button>
                        </el-radio-group>
                    </div>

                    <div id="upload-img" class="imgList" v-loading="imgLoading" element-loading-background="rgba(0, 0, 0, 0)">
                        <div class="avatar-uploader-box" v-for="(img,index) in ImgList" :key="index">
                            <img
                                    @click="chooseTheImg(img.attachment,img.url)"
                                    :src="img.url"
                                    class="avatar"
                            />
                            <i
                                    class="el-icon-circle-close"
                                    @click="deleteImg(img.id)"
                                    title="点击清除图片"
                            ></i>
                        </div>
                    </div>

                    <el-pagination
                            style="margin-top: 10px;text-align: right"
                            background
                            @current-change="currentChange"
                            :page-size="pageSize"
                            :current-page.sync="current_page"
                            :total="total"
                            layout="prev, pager, next"
                    >
                    </el-pagination>
                </el-tab-pane>
            </el-tabs>
            <span slot="footer" class="dialog-footer">
                <el-button @click="centerDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="sureImg">确 定 </el-button>
                </span>
        </el-dialog>
    </div>
</template>
<script>
    var upload_url = "{!!absolute_admin_url('common.upload.uploadTinyMce')!!}";
    //todo 测试
    Vue.component('tinymceee', {
        props: ['value','se_name'],
        delimiters: ['[[', ']]'],
        data(){
            return{
                id_name:'tinymceId_' + ((Math.random() * 1000).toFixed(0) + ''),
                flag:true,
                hasInit: false,
                hasChange: false,

                imgLoading: false,
                ImgList: [],
                //弹框上传图片的路径
                uploadImg: "",
                uploadImgUrl: "",
                netImgUrl: "",

                chooseImg: "",

                radio1: "", //年
                radio2: "", //月
                activeName2: "first",
                //是否显示弹框
                centerDialogVisible: false,
                pageSize: 0,
                current_page: 0,
                total: 0,
            }
        },
        watch:{
            value(val){
                //console.log('this.hasChange',this.hasChange);
                //console.log('this.hasInit',this.hasInit)
                if (!this.hasChange && this.hasInit) {
                    // tinyMCE.activeEditor.setContent(val);
                    this.$nextTick(() =>
                        window.tinymce.get(this.id_name).setContent(val || ''))
                }
                this.flag=true;
            },
            // img(){
            //   if(this.img){
            //       tinyMCE.activeEditor.insertContent(`<img src="${this.img}" >`)
            //     }
            // }
        },
        created(){
            window.addEventListener('beforeunload', e => {
                window.onbeforeunload =null
            });
        },
        mounted: function(){
            var component = this;
            if(this.se_name) {
                this.id_name = this.se_name;
            }

            tinymce.init({
                selector: "#"+component.id_name,
                language: "zh_CN",
                hasChange: false,
                hasInit: false,
                menubar: false,
                body_class: 'panel-body ',
                object_resizing: true, //调整尺寸
                end_container_on_empty_block: true,
                powerpaste_word_import: 'merge',
                powerpaste_html_import: 'merge',
                powerpaste_allow_local_images: true,
                code_dialog_height: 450,
                code_dialog_width: 1000,
                max_height: 1000,
                height:600,
                advlist_bullet_styles: 'square',
                advlist_number_styles: 'default',
                imagetools_cors_hosts: ['www.tinymce.com', 'codepen.io'],
                fontsize_formats: "8px 10px 12px 14px 16px 18px 20px 22px 24px 28px 30px 36px",
                default_link_target: '_blank',
                link_title: false,
                autosave_ask_before_unload: false,
                autosave_interval: '20s',
                nonbreaking_force_tab: true, // inserting nonbreaking space &nbsp; need Nonbreaking Space Plugin
                // plugins: ['advlist anchor autolink autosave code codesample colorpicker colorpicker contextmenu directionality emoticons fullscreen hr image imagetools insertdatetime link lists media nonbreaking noneditable pagebreak powerpaste preview print save searchreplace spellchecker tabfocus table template textcolor textpattern visualblocks visualchars wordcount'],
                // toolbar: ['searchreplace bold italic underline strikethrough fontsizeselect alignleft aligncenter alignright outdent indent  blockquote undo redo removeformat subscript superscript code codesample', 'hr bullist numlist link image charmap preview anchor pagebreak insertdatetime media table emoticons forecolor backcolor fullscreen'],
                plugins: ['autosave advlist anchor autolink autoresize code codesample colorpicker contextmenu directionality emoticons fullscreen hr image imagetools insertdatetime link charmap lists media nonbreaking noneditable pagebreak preview print save searchreplace spellchecker tabfocus table template textcolor textpattern visualblocks visualchars wordcount bdmap powerpaste formatpainter'],
                toolbar: ['restoredraft forecolor backcolor searchreplace bold italic underline strikethrough fontsizeselect', ' alignleft aligncenter alignright outdent indent  ltr rtl blockquote undo redo removeformat subscript superscript code codesample', 'hr bullist numlist link image charmap preview anchor pagebreak print insertdatetime media table emoticons fullscreen formatpainter'],
                image_advtab: true,
                relative_urls: false,
                remove_script_host: false,
                images_upload_url: upload_url + '&upload_type=image',
                file_picker_callback: function(callback, value, meta) {
                    //文件分类
                    var filetype = '.pdf, .jpg, .jpeg, .png, .gif, .mp3, .mp4';
                    //后端接收上传文件的地址
                    var upurl = upload_url +'&upload_type=video';
                    //为不同插件指定文件类型及后端地址
                    switch (meta.filetype) {
                        case 'image':
                            upurl = upload_url +'&upload_type=image';
                            filetype = '.jpg, .jpeg, .png, .gif';
                            break;
                        case 'media':
                            filetype = '.mp3, .mp4';
                            break;
                        case 'file':
                        default:
                    }
                    //模拟出一个input用于添加本地文件
                    var input = document.createElement('input');
                    input.setAttribute('type', 'file');
                    input.setAttribute('accept', filetype);
                    input.click();
                    input.onchange = function() {
                        var file = this.files[0];
                        const loading = component.$loading({
                            lock: true,
                            text: '正在上传',
                            spinner: 'el-icon-loading',
                            background: 'rgba(0, 0, 0, 0.7)'
                        });
                        var xhr, formData;
                        // console.log(file, file.name);
                        xhr = new XMLHttpRequest();
                        xhr.withCredentials = false;
                        xhr.open('POST', upurl);
                        xhr.onload = function() {
                            var json;
                            if (xhr.status != 200) {
                                loading.close();
                                // failure('HTTP Error: ' + xhr.status);
                                return;
                            }
                            json = JSON.parse(xhr.responseText);
                            if (!json || typeof json.location != 'string') {
                                // failure('Invalid JSON: ' + xhr.responseText);
                                return;
                            }
                            loading.close();
                            callback(encodeURI(json.location), {
                                title: file.name
                            });
                        };
                        formData = new FormData();
                        formData.append('file', file, file.name);
                        xhr.send(formData);
                    };
                },
                media_url_resolver: (data, resolve)=> {
                    try {
                        let videoUri = encodeURI(data.url);
                        if(data.url.indexOf('.mp4')>-1) {
                            // 判断是否mp4  否则用ifarme嵌套
                            let embedHtml = `<p>
                                    <video src=${ data.url } width="100%" height="auto" style="max-width: 100%;" allowfullscreen="false" controls="controls" controlslist="nodownload">
                                    </video>
                                </p>`;
                            resolve({ html: embedHtml });
                        }else {
                            let embedHtml = `<p>
                                    <iframe frameborder="0" src=${ data.url } width="100%" height="100%" style="max-width: 100%;">
                                    </iframe>
                                </p>`;
                            resolve({ html: embedHtml });
                        }

                    } catch (e) {
                        resolve({ html: "" });
                    }
                },
                init_instance_callback: editor => {
                    console.log('init_instance_callback');
                    if (this.value) {
                        editor.setContent(this.value)
                    }
                    this.hasInit = true
                    editor.on('NodeChange Change KeyUp SetContent', () => {
                        this.hasChange = true
                        this.$emit('input', editor.getContent())
                    })
                },
                save_onsavecallback() {
                    console.log('阻止默认保存')
                }
            });
        },
        methods:{
            setContent(value) {
                window.tinymce.get(this.tinymceId).setContent(value)
            },
            getContent() {
                window.tinymce.get(this.tinymceId).getContent()
            },
            destroyTinymce() {
                const tinymce = window.tinymce.get(this.tinymceId)
                if (this.fullscreen) {
                    tinymce.execCommand('mceFullScreen')
                }

                if (tinymce) {
                    tinymce.destroy()
                }
            },


            chooseTheImg(img,img_url) {
                if(img_url){
                    tinyMCE.activeEditor.insertContent(`<img src="${img_url}" data-mce-src="${img_url}">`)
                }
                this.centerDialogVisible = false;
            },

            chooseYear(year) {
                this.currentChange(1);
            },
            chooseMonth(month) {
                this.currentChange(1);
            },
            openUpload() {
                this.uploadImgUrl = "";
                this.netImgUrl = "";
                this.centerDialogVisible = true;
                this.initData();
                this.currentChange(1);
            },
            sureImg() {
                if(this.uploadImgUrl){
                    tinyMCE.activeEditor.insertContent(`<img src="${this.uploadImgUrl}" >`)
                }
                this.centerDialogVisible = false;
            },
            // 转化网络地址
            transform() {
                if(!this.netImgUrl) {
                    this.$message.error("请输入网络地址")
                    return;
                }
                this.imgLoading = true;
                this.$http
                    .post("{!! absolute_admin_url('upload.uploadV2.fetch') !!}", { url: this.netImgUrl }).then(response => {
                    if (response.data.result === 1) {
                        if(response.data.data.img_url){
                            tinyMCE.activeEditor.insertContent(`<img src="${response.data.data.img_url}" >`)
                        }
                        this.centerDialogVisible = false;
                    } else {
                        this.$message.error(response.data.msg);
                    }
                    this.imgLoading = false;
                })
                    .catch(err => {
                        console.error(err);
                        this.imgLoading = false;

                    });
            },
            currentChange(val) {
                this.imgLoading = true;
                this.$http.post("{!! absolute_admin_url('common.upload.getImageList') !!}"+'&group_id=-999&local=local',{ page: val, year: this.radio1, month: this.radio2 })
                    .then(response => {
                        console.log(response)

                        if (response.data.result == 1) {
                            this.total = response.data.data.total;
                            this.ImgList = response.data.data.data;
                            this.current_page = response.data.data.current_page;
                            this.pageSize = response.data.data.per_page;
                        } else {
                            this.$message.error(response.data.msg);
                        }
                        this.imgLoading = false;
                    })
                    .catch(err => {
                        console.error(err);
                        this.imgLoading = false;
                    });
            },
            clearImg(str) {
                this.form[str] = "";
                this.form[str+'_url'] = "";
            },
            deleteImg(id) {
                this.imgLoading = true;
                this.$http
                    .post("{!! absolute_admin_url('common.upload.delete') !!}", { id: id })
                    .then(response => {
                        if (response.data.result == 1) {
                            this.$message.success("系统删除成功");
                            this.currentChange(1);
                        } else {
                            this.$message.error(response.data.msg);
                        }
                        this.imgLoading = false;
                    })
                    .catch(err => {
                        console.error(err);
                        this.imgLoading = false;
                    });
            },
            uploadSuccess(res, file) {
                console.log(res)
                if (res.result == 1) {
                    if (res.data.state == 'SUCCESS') {
                        this.uploadImg = res.data.attachment;//传相对地址
                        this.uploadImgUrl = res.data.url;
                        this.$message.success("上传成功！");
                    } else {
                        this.$message.error(res.msg);
                    }
                } else {
                    this.$message.error(res.msg);
                }
                this.imgLoading = false;
            },
            beforeUpload(file) {
                this.imgLoading = true;
                const isLt2M = file.size / 1024 / 1024 < 4;
                if (!isLt2M) {
                    this.$message.error("上传图片大小不能超过 4MB!");
                    this.imgLoading = false;
                }
                return isLt2M;
            },
            initData() {
                this.imgLoading= false;
                this.ImgList= [];
                //弹框上传图片的路径
                this.uploadImg= "";
                this.uploadImgUrl= "";
                this.netImgUrl= "";

                this.chooseImg= "";

                this.radio1= "", //年
                    this.radio2= "", //月
                    this.activeName2= "first";
                //是否显示弹框
                // this.centerDialogVisible= false;
                this.pageSize= 0;
                this.current_page= 0;
                this.total= 0;
            }
        },
        template: '#tinymceee'
    });
</script>

